from django.contrib.auth import authenticate
from django.utils.cache import patch_vary_headers
from oauth2_provider.compat import MiddlewareMixin


class MyMiddleware(MiddlewareMixin):

    def process_request(self, request):
        print("xxxxxxxxxxxxxxxxxxxx", request)
        # do something only if request contains a Bearer token
        if request.META.get("HTTP_AUTHORIZATION", "").startswith("Bearer"):
            if not hasattr(request, "user") or request.user.is_anonymous:
                user = authenticate(request=request)
                if user:
                    request.user = request._cached_user = user
                    print("ok", request.user.is_anonymous)
            else:
                print("x", request.user.is_anonymous)
        print(request.META.get('HTTP_AUTHORIZATION'))

    def process_response(self, request, response):
        patch_vary_headers(response, ("Authorization",))
        return response
